package com.mytijian.utils;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.mytijian.exception.BizSystemException;
import com.mytijian.exception.CommonExceptionEnum;

public class BeanUtil {
	
	public static <T> T createObject(Object source, Class<T> targetCls) {
		if(source == null){
			return null;
		}
		T targetObj = createObject(targetCls);
		BeanUtils.copyProperties(source, targetObj);
		return targetObj;
	}

	private static <T> T createObject(Class<T> targetCls) {
		try {
			return targetCls.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			throw new BizSystemException(CommonExceptionEnum.CREATE_OBJECT_ERROR, e);
		}
	}
	
	/**
	 * 使用spring beanUtil copy对象属性
	 * @param srcList
	 * @param targetClass
	 * @return
	 */
	public static <E, T> List<T> copyBeanList(List<E> srcList, Class<T> targetClass){
		List<T> list = new ArrayList<>();
		if (srcList!=null && !srcList.isEmpty()) {
			srcList.forEach(src->{
				try {
					T target = targetClass.newInstance();
					BeanUtils.copyProperties(src, target);
					list.add(target);
				} catch (Exception e) {
					throw new BizSystemException(CommonExceptionEnum.BEAN_COPY_ERROR, e);
				}
			});
		}
		return list;
	}
}
